import sys
import os
import django
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(BASE_DIR)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'application.settings')
django.setup()
import consul
from application import settings


class Consul(object):
    def __init__(self, host, port):
        '''初始化，连接consul服务器'''
        self._consul = consul.Consul(host, port)

    def RegisterService(self, name, host, port, tags=None):
        tags = tags or []
        # 注册服务
        self._consul.agent.service.register(
            name,
            name,
            host,
            port,
            tags,
            # 健康检查ip端口，检查时间：5,超时时间：30，注销时间：30s
            check=consul.Check().tcp(host, port, "5s", "30s", "30s"))

    def GetService(self, name):
        services = self._consul.agent.services()
        service = services.get(name)
        if not service:
            return None, None
        addr = "{0}:{1}".format(service['Address'], service['Port'])
        return service, addr


def register_consul():
    try:
        print('==========register consul==============')
        consul_host = settings.CONSUL_HOST
        consul_port = settings.CONSUL_PORT
        service_name = settings.SERVICE_NAME
        service_host = settings.SERVICE_HOST
        service_port = settings.SERVICE_PORT

        consul_client = Consul(consul_host, consul_port)
        consul_client.RegisterService(service_name, service_host, service_port)
        check = consul.Check().tcp(service_host, service_port, "5s", "30s", "30s")
        print(check)
        res = consul_client.GetService(service_name)
        print(res)
        print('==========register consul complate==============')

    except Exception as e:
        print("初始化consul连接失败：" + e)


if __name__ == '__main__':
    register_consul()
